<template>
    <div class="student-add-container">
        <el-card>
            <template #header>
                <span>{{ isEdit ? '编辑学生信息' : '新增学生' }}</span>
            </template>
            <el-form :model="studentForm" label-width="100px" :rules="rules" ref="formRef">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="studentForm.userName" :disabled="isEdit" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="!isEdit">
                    <el-input v-model="studentForm.password" type="password" />
                </el-form-item>
                <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="studentForm.realName" />
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="studentForm.age" :min="15" :max="30" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="studentForm.sex">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthDay">
                    <el-date-picker v-model="studentForm.birthDay" type="date" placeholder="选择出生日期" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="studentForm.phone" />
                </el-form-item>
                <el-form-item label="年级" prop="userLevel">
                    <el-input-number v-model="studentForm.userLevel" :min="1" :max="4" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="studentForm.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="clean" :disabled="isEdit">重置</el-button>
                    <el-button type="danger" @click="router.push('/student')">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-card>
    </div>
</template>
<script setup>
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ref, onMounted } from 'vue'

const router = useRouter()
const formRef = ref(null)
const isEdit = ref(false)
const clean = () => {
    initForm();
    // 如果有 formRef，重置校验状态
    formRef.value && formRef.value.resetFields();
};

// 表单数据
const studentForm = ref({
    id: null,
    userName: "",
    password: "",
    realName: "",
    age: null,
    role: 1,
    sex: 1,
    birthDay: "",
    phone: "",
    status: 1,
    userLevel: 1
})

// 初始化表单数据
const initForm = () => {
    studentForm.value = {
        id: null,
        userName: "",
        password: "",
        realName: "",
        age: null,
        role: 1,
        sex: 1,
        birthDay: "",
        phone: "",
        status: 1,
        userLevel: 1
    }
}


// 表单验证规则
const rules = {
    userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    userLevel: [{ required: true, message: '请输入年级', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}


onMounted(() => {
    if (localStorage.getItem('isEdit') === '1') {
        const data = localStorage.getItem('editStudent')
        if (data) {
            studentForm.value = JSON.parse(data)
            isEdit.value = true
        }
        // 用完清理，避免新增时被污染
        localStorage.removeItem('editStudent')
        localStorage.removeItem('isEdit')
    }
})

import { add } from '@/api/student'

const submitForm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                let res
                if (isEdit.value) {
                    // 编辑
                    res = await add(studentForm.value)
                    if (res.code === 1) {
                        ElMessage.success('成功')
                        router.push("/student")
                    } else {
                        ElMessage.error(res.msg || '失败')
                    }
                } else {
                    // 添加
                    res = await add(studentForm.value)
                    if (res.code === 1) {
                        ElMessage.success('成功')
                        router.push("/student")
                    } else {
                        ElMessage.error(res.msg || '失败')
                    }
                }

            } catch (error) {
                ElMessage.error(error.message || '失败')
            }
        }
    })
}
</script>
<style></style>